package com.itmk.business.contact.controller;

import com.itmk.business.contact.entity.Contact;
import com.itmk.business.contact.entity.ContactCategory;
import com.itmk.business.contact.service.ContactCategoryService;
import com.itmk.business.contact.service.ContactService;
import com.itmk.config.redis.RedisUtils;
import com.itmk.constants.Constant;
import com.itmk.result.DataResult;
import com.itmk.system.common.service.RedisService;
import com.itmk.utils.PageUtil;
import com.itmk.utils.QiniuCloudUtil;
import com.itmk.utils.UpPhotoNameUtil;
import com.itmk.vo.req.ContactReqVO;
import com.itmk.vo.resp.PageRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/contact")
@Api(tags = "联系人管理")
public class ContactController {
    @Autowired
    private ContactService contactService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ContactCategoryService contactCategoryService;

    @Autowired
    private QiniuCloudUtil qiniuCloudUtil;

    @ApiOperation(value = "获取联系人列表")
    @RequestMapping(value = "/getcontactlist", method = RequestMethod.POST)
    public DataResult getContactList(@RequestBody ContactReqVO vo) {
        List<Object> result = contactService.getContactsByProcedure(vo);
        PageRespVO<Object> pageRespVO= PageUtil.getPageVo(result);
        return DataResult.success(pageRespVO);
    }

    @ApiOperation(value = "根据Id获取联系人")
    @RequestMapping(value = "/getcontactbyid", method = RequestMethod.POST)
    public DataResult getContactById(@RequestBody Contact p) {
        Contact contact = contactService.getById(p.getContactId());
        return DataResult.success(contact);

    }

    @ApiOperation(value = "根据Id删除联系人")
    @RequestMapping(value = "/deletecontactbyid", method = RequestMethod.POST)
    public DataResult deleteContactById(@RequestBody Contact c) {
        Boolean b = contactService.removeById(c.getContactId());
        if (b) {
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "删除失败!");
        }
    }

    @ApiOperation(value = "新增联系人")
    @RequestMapping(value = "/addcontact", method = RequestMethod.POST)
    public DataResult addContact(@RequestBody Contact c) {
        Boolean b=this.contactService.save(c);
        if(b){
            return DataResult.success();
        }else{
            return DataResult.getResult(300100, "新增联系人失败!");
        }
    }

    @ApiOperation(value = "更新联系人")
    @RequestMapping(value = "/updatecontact", method = RequestMethod.POST)
    public DataResult updateContact(@RequestBody Contact c) {

        Boolean b = this.contactService.updateById(c);
        if (b) {
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "更新失败!");
        }

    }

    @ApiOperation(value = "上传联系人头像")
    @RequestMapping(value = "/uploadcontactimg", method = RequestMethod.POST)
    public DataResult uploadContactImg(@RequestParam("file") MultipartFile file) {

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtil.getPhotoName("img",imageFileName);
            Path path = Paths.get(Constant.CONTACT_PHOTO_PATH + fileName);
            Files.write(path, bytes);
            System.out.println(fileName+"\n");
            return DataResult.success(fileName);
        } catch ( IOException e) {
            e.printStackTrace();
        }
        return DataResult.getResult(300100, "上传失败!");

    }


    @ApiOperation(value = "上传联系人头像2")
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public DataResult uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return DataResult.getResult(300100,"文件不能为空");
        }
        try {
            byte[] bytes = file.getBytes();
            String imageName = UUID.randomUUID().toString();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuCloudUtil.put64image(bytes, imageName);
                return DataResult.success(url);
            } catch (Exception e) {
                e.printStackTrace();
                return DataResult.getResult(300100,"上传图片异常");
            }
        } catch (IOException e) {
            return DataResult.getResult(300100,"上传图片异常");
        }
    }


    @ApiOperation(value = "删除联系人头像")
    @RequestMapping(value = "/deletecontactimg", method = RequestMethod.POST)
    public DataResult deletecontactimg(@RequestBody Contact c) {
        try {
            Boolean flag=qiniuCloudUtil.delete(c.getPhoto()); // 删除照片
            if (flag) {
                return DataResult.success();
            } else {
                return DataResult.getResult(300100, "删除失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.getResult(300100, "图片不存在或其它异常!");
        }

    }

    @ApiOperation(value = "获取联系人分类列表")
    @RequestMapping(value = "/getcontactcategorylist", method = RequestMethod.POST)
    public DataResult getContactCategoryList() {
        List<ContactCategory> contactCategories=new ArrayList<>();
        if(redisService.hasKey(Constant.CONTACTCATEOGRY_REDIS_KEY)){
            contactCategories= RedisUtils.RedisToObjectList(redisService.get(Constant.CONTACTCATEOGRY_REDIS_KEY).toString(), ContactCategory.class);
        }else {
            contactCategories = this.contactCategoryService.list();
            redisService.set(Constant.CONTACTCATEOGRY_REDIS_KEY,contactCategories,10, TimeUnit.MINUTES);
        }
        log.info("{}",contactCategories);
        return DataResult.success(contactCategories);
    }

    @ApiOperation(value = "新增联系人分类")
    @RequestMapping(value = "/addcontactcategory", method = RequestMethod.POST)
    public DataResult addContactCategory(@RequestBody ContactCategory c) {
        Boolean b=this.contactCategoryService.save(c);
        if(b){
            redisService.delete(Constant.CONTACTCATEOGRY_REDIS_KEY);
            return DataResult.success();
        }else{
            return DataResult.getResult(300100, "新增联系人分类失败!");
        }
    }

    @ApiOperation(value = "根据Id删除联系人分类")
    @RequestMapping(value = "/deletecontactcategorybyid", method = RequestMethod.POST)
    public DataResult deleteContactCategoryById(@RequestBody ContactCategory c) {
        Boolean b = contactCategoryService.removeById(c.getContactCategoryId());
        if (b) {
            redisService.delete(Constant.CONTACTCATEOGRY_REDIS_KEY);
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "删除失败!");
        }
    }

    @ApiOperation(value = "更新联系人分类")
    @RequestMapping(value = "/updatecontactcategory", method = RequestMethod.POST)
    public DataResult updateContactCategory(@RequestBody ContactCategory c) {

        Boolean b = this.contactCategoryService.updateById(c);
        if (b) {
            redisService.delete(Constant.CONTACTCATEOGRY_REDIS_KEY);
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "更新失败!");
        }

    }




}
